package cn.lau.common.config;

import cn.lau.common.security.CustomUserDetailsService;
import cn.lau.common.security.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private CustomUserDetailsService customUserDetailsService;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests()
        .antMatchers("/home").permitAll() //访问：/home 无需登录认证权限
        .anyRequest().authenticated()  //其他所有资源都要认证，登录访问
        .antMatchers("/hello").hasAnyAuthority("ADMIN") //登陆后 拥有ADMIN权限的才可访问 /hello，反正系统出现403权限不足提示
        .and()
        .formLogin()
        .loginPage("/login") //指定登录页是 "/login"
        .permitAll()
        .successHandler(loginSuccessHandler())
        .and()
        .logout()
        .logoutUrl("/home") //退出登录后默认网址是"/home"
        .permitAll()
        .invalidateHttpSession(true)
        .and()
        .rememberMe() //登录后记住用户下次自动登录，数据库必须存在名为persisten_logins的表
        .tokenValiditySeconds(1209600);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //指定密码加密所使用的加密器为passwordEncoder()
        //需要将密码加密后写入数据库
        auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());

        super.configure(auth);
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder(4);
    }

    @Bean
    public LoginSuccessHandler loginSuccessHandler(){
        return new LoginSuccessHandler();
    }
}
